//
//  KYHttpClient.m
//  KYAdvertSDK
//
//  Created by 01 on 17/4/9.
//  Copyright © 2017年 蔡正军. All rights reserved.
//

#import "KYHttpClient.h"
#import "KYAFNetworking.h"
#import <objc/runtime.h>
#import "KYDeviceInfoModel.h"

@implementation KYAFHTTPRequestOperationManager (requestMethod)

- (KYAFHTTPRequestOperation *)sendRequest:(NSString *)URLString
                            requestMethod:(NSString *)requestMethod
                               parameters:(id)parameters
                                  success:(void (^)(KYAFHTTPRequestOperation *operation, id responseObject))success
                                  failure:(void (^)(KYAFHTTPRequestOperation *operation, NSError *error))failure {
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:requestMethod URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
    KYAFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
    [self.operationQueue addOperation:operation];
    return operation;
}

@end

static inline NSString * HTTPUserAgent() {
    
    NSString *userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iPhone iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
    
    if (userAgent)
    {
        if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding])
        {
            NSMutableString *mutableUserAgent = [userAgent mutableCopy];
            if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false))
            {
                userAgent = mutableUserAgent;
            }
        }
    }
    return userAgent;
}


@implementation KYHttpClient

+ (NSOperation *)sendRequest:(NSString *)url
               requestMethod:(NSString *)requestMethod
                  parameters:(NSDictionary *)parameters
                     success:(void (^)(id responseObject))success
                     failure:(void (^)(NSUInteger statusCode, NSString *error))failure
{
    KYAFHTTPRequestOperationManager *manager = [KYAFHTTPRequestOperationManager manager];
    
    
    // 2.设置非校验证书模式
    manager.securityPolicy = [KYAFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.securityPolicy.allowInvalidCertificates = YES;
    [manager.securityPolicy setValidatesDomainName:NO];
    
    
#if !TARGET_ENV_PRD
    manager.securityPolicy.allowInvalidCertificates = YES;  // 测试环境允许无效证书
#endif
    
    // 设置请求
    KYAFHTTPRequestSerializer *requestSerializer = [KYAFHTTPRequestSerializer serializer];
    requestSerializer.timeoutInterval = 28;
    NSString *userAgent = HTTPUserAgent();
    [requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    [requestSerializer setValue:userAgent forHTTPHeaderField:@"eppUserAgent"];
    manager.requestSerializer = requestSerializer;
    
    // 设置响应
    KYAFHTTPResponseSerializer *responseSerializer = [KYAFJSONResponseSerializer serializer];
    NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:responseSerializer.acceptableContentTypes];
    [acceptableContentTypes addObject:@"text/html"];
    responseSerializer.acceptableContentTypes = acceptableContentTypes;
    manager.responseSerializer = responseSerializer;
    manager.responseSerializer = [KYAFHTTPResponseSerializer serializer];
    
    //    KYAFJSONResponseSerializer  *response = [KYAFJSONResponseSerializer serializer];
    //
    //    response.removesKeysWithNullValues = YES;
    //
    //    manager.responseSerializer = response;
    
    
    NSOperation *operation = [manager sendRequest:url requestMethod:requestMethod parameters:parameters success:^(KYAFHTTPRequestOperation *operation, id responseObject)
                              {
                                  //                                      KYLog(@"未实现回调Block");
                                  NSError *err = nil;
                                  NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&err];
                                  if(!err){if (success){success(dict);}}
                              } failure:^(KYAFHTTPRequestOperation *operation, NSError *error) {
                                  NSString *tError = nil;
                                  switch ([error code]) {
                                          case NSURLErrorTimedOut:
                                          tError = [NSString stringWithFormat:@"连接服务器超时, 请检查你的网络或稍后重试"];
                                          break;
                                          case NSURLErrorBadURL:
                                          case NSURLErrorUnsupportedURL:
                                          case NSURLErrorCannotFindHost:
                                          case NSURLErrorDNSLookupFailed:
                                          case NSURLErrorCannotConnectToHost:
                                          case NSURLErrorNetworkConnectionLost:
                                          case NSURLErrorNotConnectedToInternet:
                                          case NSURLErrorUserCancelledAuthentication:
                                          case NSURLErrorUserAuthenticationRequired:
                                          case NSURLErrorSecureConnectionFailed:
                                          case NSURLErrorServerCertificateHasBadDate:
                                          case NSURLErrorServerCertificateUntrusted:
                                          case NSURLErrorServerCertificateHasUnknownRoot:
                                          case NSURLErrorServerCertificateNotYetValid:
                                          case NSURLErrorClientCertificateRejected:
                                          case NSURLErrorClientCertificateRequired:
                                          tError = [NSString stringWithFormat:@"无法连接到服务器, 请检查你的网络或稍后重试"];
                                          break;
                                          
                                          case NSURLErrorHTTPTooManyRedirects:
                                          tError = [NSString stringWithFormat:@"太多HTTP重定向, 请检查你的网络或稍后重试"];
                                          break;
                                          
                                      default:
                                          tError = [NSString stringWithFormat:@"系统繁忙，请稍后再试"];
                                          break;
                                  }
//                                  KYLog(@"网络错误编码：%ld",(long)[error code]);
                                  if (failure) failure([error code], tError);
                              }];
    return operation;
}

+ (NSMutableDictionary *)uaDic{
    NSMutableDictionary *userDic = [NSMutableDictionary dictionary];
    unsigned int count = 0;
    KYDeviceInfoModel *model = [KYDeviceInfoModel deviceInfoModel];
    objc_property_t *properties = class_copyPropertyList([model class], &count);
    for (int i = 0; i < count; i++) {
        const char *name = property_getName(properties[i]);
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id propertyValue = [model valueForKey:propertyName];
        if (propertyValue) {
            [userDic setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return userDic;
}

@end
